﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Xml;
using System.Net;
using System.Data;
using System.IO;

namespace Jp.NicoVideo.Live.Api
{
    public class Message
    {
        private PlayerStatusDataSet playerStatus = null;
        private string liveId = null;

        public Message(PlayerStatusDataSet status, string liveId)
        {
            playerStatus = status;
            this.liveId = liveId;
        }

        /// <summary>
        /// コメント受信時に実行されるメソッド
        /// </summary>
        /// <param name="message">受信したメッセージ</param>
        void OnReceiveChat(string message)
        {
            Console.WriteLine(message);

            /*			
                todo 
            */
            switch(message)
            {
                case "get9":
                {
                    Broadcast.SendComment("/play sm384946 sub", liveId);
                    break;
                }
                case "stop":
                {
                    Broadcast.SendComment("/stop sub", liveId);
                    break;
                }
            }
        }

        /// <summary>
        /// メッセージサーバからメッセージを取得する
        /// コメント受信時にOnReceiveChatメソッドが実行される。 
        /// </summary>
        /// <param name="liveInfo">接続用の情報</param>
        public void ReceiveChat()
        {
#if false
            using (TcpClient client = new TcpClient(playerStatus.ms[0].addr, playerStatus.ms[0].port))
            using (NetworkStream stream = client.GetStream())
            using (XmlReader reader = XmlReader.Create(stream))
            using (DataTable table = new DataTable())
            {
                string sendMessage = String.Format("<thread thread=\"{0}\" res_from=\"{1}\" version=\"20061206\" /> ", playerStatus.ms[0].thread, -2);
                byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
                sendBytes[sendBytes.Length - 1] = 0;
                stream.Write(sendBytes, 0, sendBytes.Length);

                table.RowChanged += delegate(object sender, DataRowChangeEventArgs args)
                {
                    foreach (object obj in args.Row.ItemArray)
                    {
                        Console.WriteLine(obj);
                    }
                };
                table.ReadXml(reader);
            }
#else
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (TcpClient tcp = new TcpClient(playerStatus.ms[0].addr, playerStatus.ms[0].port))
            using (NetworkStream ns = tcp.GetStream())
            {
                Console.WriteLine("完了");

                string msg = String.Format("<thread thread=\"{0}\" res_from=\"{1}\" version=\"20061206\" />\0", playerStatus.ms[0].thread, -2);
                byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(msg);

                ns.Write(sendBytes, 0, sendBytes.Length);

                byte[] resBytes = new byte[4096];
                int resSize;
                do
                {

                    resSize = ns.Read(resBytes, 0, resBytes.Length);

                    if (resSize == 0)
                    {
                        break;
                    }

                    string chat = enc.GetString(resBytes);

                    //メッセージ受信を伝達
                    //if (!chat.StartsWith("<thread"))
                    //{
                        OnReceiveChat(GetMessage(chat));
                    //}

                } while (ns.CanRead);

                //閉じる
                tcp.Close();
                Console.WriteLine("切断しました。");
            }
#endif
        }

        /// <summary>
        /// メッセージサーバから送られてきた文字列からメッセージ部分だけを取り出す
        /// </summary>
        /// <param name="chatStr">サーバーレスポンスを文字列にしたもの</param>
        /// <returns>投稿されたメッセージ</returns>
        static string GetMessage(string chatStr)
        {
            string pattern = ">([^<>]*)";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);
            System.Text.RegularExpressions.Match match = reg.Match(chatStr);

            return Unsanitizing(match.Groups[1].Value);
        }

        /// <summary>
        /// アンサニタライズ
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        static string Unsanitizing(string src)
        {
            src = src.Replace("&amp;", "&");
            src = src.Replace("&lt;", "<");
            src = src.Replace("&gt;", ">");
            src = src.Replace("&quot;", "\"");
            src = src.Replace("&#39;", "'");

            return src;
        }
    }
}
